import React from "react";
import { useForm } from "react-hook-form";
import { useRequest } from "ahooks";
import dayjs from "dayjs";
import { Button } from "@/components/ui/button";
import request from "@/api/http_class";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { zodResolver } from "@hookform/resolvers/zod";
import { ColumnDef, createColumnHelper } from "@tanstack/react-table";
import { ArrowUpDown, CalendarIcon } from "lucide-react";
import { Edit, MoreHorizontal, Trash } from "lucide-react";
import { useNavigate } from "react-router-dom";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import { VbpBatchI } from "@/types";
import PageContainer from "@/components/layout/page-container";
import CustomTable from "@/components/ui/custom-table";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { Plus } from "lucide-react";
import {
  createVbpBatch,
  updateVbpBatch,
  searchVbpBatchList,
  deleteVbpBatch,
} from "@/api";
import { useSearchParams, Link } from "react-router-dom";
import { CustomDatePicker } from "@/components/ui/datepicker";

const formSchema = z.object({
  id: z.string().optional(),
  hisCode: z.string().trim(),
  startDate: z.date({ required_error: "请输入批次开始时间" }),
  endDate: z.date({ required_error: "请输入批次结束时间" }),
  atcCode: z.string().trim(),
  vbpClass: z.string().trim(),
  monitorClass: z.string().trim(),
  drugname: z.string().trim(),
  specification: z.string().trim(),
  miniUnit: z.string().trim(),
  packSize: z.number(),
  packUnit: z.string().trim(),
  pinyin: z.string().trim(),
  py: z.string().trim(),
  manuName: z.string().trim(),
  dutyAmount: z
    .number()
    .int()
    .min(0, "任务量不应小于0")
    .max(10000000000, "任务量不应大于10000000000"),
  batch: z.string().trim().optional(),
  cadn: z.string().trim(),
  calcFactor: z.number(),
  status: z.number().int().min(0, "状态不会小于0").max(10, "状态不会大于10"),
});

type FormValuesT = z.infer<typeof formSchema>;

const page: React.FC = () => {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();

  const [title, setTitle] = React.useState<string>("");
  const [description, setDescription] = React.useState<string>("");
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false);
  const [isAlertOpen, setIsAlertOpen] = React.useState<boolean>(false);
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [vbpBatchList, setVbpBatchList] = React.useState<VbpBatchI[]>([]);
  const [formData, setFormData] = React.useState<VbpBatchI>();
  // const [myDate, setMyDate] = React.useState<Date>();

  const { loading: loadingList, run } = useRequest(
    (paramsString: string) => searchVbpBatchList(paramsString),
    {
      manual: true,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params: any) {
        // console.log(resp.data.data);
        setVbpBatchList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(e: any, params: any) {
        console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: "请检查网络或联系系统管理员",
        });
      },
    }
  );

  const handleUploadSubmit = (values: any): Promise<any> => {
    console.log(values);
    return new Promise((resolve, reject) => {
      if (values.files.length) {
        const formData = new FormData();
        // 将全部数据转换为FormData格式
        values.files.forEach((item: File) => {
          console.log(item);
          formData.append("files", item);
        });
        console.log(formData);
        request({
          url: `/vbp-batch/import/`,
          method: "POST",
          data: formData,
          headers: { "Content-Type": "multipart/form-data" },
        }).then(
          (res: any) => {
            console.log(res);
            resolve(res);
            toast({
              variant: "success",
              title: "数据导入成功",
              description: "",
            });
          },
          (err: any) => {
            console.log(err);
            reject(err);
            toast({
              variant: "destructive",
              title: "数据导入失败",
              description: "请检查网络或联系系统管理员",
            });
          }
        );
      } else {
        reject("no files");
      }
    });
  };

  React.useEffect(() => {
    run(searchParams.toString());
  }, [searchParams]);

  const onUpdateClick = (event: any, data: VbpBatchI) => {
    const processedData = Object.assign(
      {},
      defaultValues,
      Object.fromEntries(
        Object.entries(data).reduce((acc, [key, value]) => {
          if (value !== null) {
            // 如果 key 是 'startDate' 并且 value 是一个有效的日期字符串，转换为 Date
            if (key === "startDate" && !isNaN(Date.parse(value))) {
              acc.push([key, new Date(value)]);
            } else if (key === "endDate" && !isNaN(Date.parse(value))) {
              acc.push([key, new Date(value)]);
            } else {
              acc.push([key, value]);
            }
          }
          return acc;
        }, [] as [string, any][])
      )
    );
    console.log(processedData);
    setTitle("修改信息");
    // 避免将受控组件的值设置成null，否则会有警告，影响未知
    form.reset(processedData);
    setFormData(processedData);
    setIsDialogOpen(true);
    run(searchParams.toString());
  };

  const onDeleteConfirm = (event: any, data: VbpBatchI) => {
    try {
      setIsSubmitting(true);
      if (data.id) {
        deleteVbpBatch(data.id).then((res: any) => {
          console.log(data);
          console.log(res);
          toast({
            title: "删除成功",
            description: "",
          });
          run(searchParams.toString());
        });
      }
    } catch (error: any) {
      console.log(error);
      toast({
        title: "删除失败",
        description: "error",
      });
    } finally {
      setIsSubmitting(false);
      setIsAlertOpen(false);
    }
  };

  const columnHelper = createColumnHelper<VbpBatchI>();

  // const columns: ColumnDef<VbpBatchI>[] = [
  const columns = [
    columnHelper.display({
      id: "select",
      header: (props) => {
        // console.log(props);
        if (props && props.table) {
          return (
            <Checkbox
              checked={props.table.getIsAllPageRowsSelected()}
              onCheckedChange={(value) =>
                props.table.toggleAllPageRowsSelected(!!value)
              }
              aria-label="Select all"
            />
          );
        } else {
          return <Checkbox aria-label="Select all" />;
        }
      },
      footer: (props) => props.column.id,
      cell: (props) => {
        console.log(props);
        if (props && props.row) {
          return (
            <Checkbox
              checked={props.row.getIsSelected()}
              onCheckedChange={(value) => props.row.toggleSelected(!!value)}
              aria-label="Select row"
            />
          );
        } else {
          return <Checkbox aria-label="Select row" />;
        }
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("id", {
      id: "id",
      header: "ID",
      footer: (props) => props.column.id,
      cell: ({ row }) => {
        return <span>{row.getValue("id")}</span>;
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("hisCode", {
      id: "hisCode",
      header: "HIS代码",
      cell: ({ row }) => {
        return <span>{row.getValue("hisCode")}</span>;
      },
      enableSorting: true,
      enableColumnFilter: true,
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("drugname", {
      id: "drugname",
      header: "药品名称",
      enableColumnFilter: true,
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("specification", {
      id: "specification",
      header: "包装规格",
      minSize: 200,
      footer: (props) => props.column.id,
      enableColumnFilter: true,
      enableResizing: true,
    }),
    columnHelper.accessor("packSize", {
      id: "packSize",
      header: "包装量",
      minSize: 100,
      footer: (props) => props.column.id,
      enableColumnFilter: true,
      enableResizing: true,
    }),
    columnHelper.accessor("manuName", {
      id: "manuName",
      header: "生产厂商",
      size: 200,
      minSize: 200,
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("startDate", {
      id: "startDate",
      header: "开始时间",
      // minSize: 200,
      size: 200,
      enableColumnFilter: false,
      cell: (props) => {
        if (props && props.row)
          if (!isNaN(Date.parse(props.row.getValue("startDate")))) {
            return (
              <span>
                {dayjs(props.row.getValue("startDate")).format("YYYY-MM-DD")}
              </span>
            );
          } else {
            return <></>;
          }
      },
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("endDate", {
      id: "endDate",
      header: "结束时间",
      cell: (props) => {
        if (props && props.row) {
          if (!isNaN(Date.parse(props.row.getValue("endDate")))) {
            return (
              <span>
                {dayjs(props.row.getValue("endDate")).format("YYYY-MM-DD")}
              </span>
            );
          }
        } else {
          return <></>;
        }
      },
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("atcCode", {
      id: "atcCode",
      header: "ATC编码",
      minSize: 150,
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("vbpClass", {
      id: "vbpClass",
      header: "集采类别",
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("monitorClass", {
      id: "monitorClass",
      header: "监测类别",
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("dutyAmount", {
      id: "dutyAmount",
      header: "任务量",
      size: 300,
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>
                {row.getValue("dutyAmount")}
                {row.original.miniUnit}
              </span>
              /
              <span>
                {Math.ceil(
                  (row.getValue("dutyAmount") as any) /
                    ((row.original.packSize as any) || 1)
                )}
                {row.original.packUnit}
              </span>
            </div>
          );
        }
      },
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("batch", {
      id: "batch",
      header: "批次",
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("cadn", {
      id: "cadn",
      header: "通用名",
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("calcFactor", {
      id: "calcFactor",
      header: "计算系数",
      footer: (props) => props.column.id,
    }),
    columnHelper.accessor("status", {
      id: "status",
      header: "统计状态",
      footer: (props) => props.column.id,
    }),
    columnHelper.display({
      id: "actions",
      header: "操作",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <>
              <AlertModal
                isOpen={isAlertOpen}
                onClose={() => setIsAlertOpen(false)}
                onConfirm={() => onDeleteConfirm(event, row.original)}
                loading={isSubmitting}
              />
              <DropdownMenu modal={false}>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="h-8 w-8 p-0">
                    <span className="sr-only">选项</span>
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel></DropdownMenuLabel>
                  <DropdownMenuItem
                    onClick={() => onUpdateClick(event, row.original)}
                  >
                    <Edit className="mr-2 h-4 w-4" /> 更新
                  </DropdownMenuItem>
                  {/* <DropdownMenuItem onClick={() => setIsAlertOpen(true)}>
                  <Trash className="mr-2 h-4 w-4" /> 删除
                </DropdownMenuItem> */}
                </DropdownMenuContent>
              </DropdownMenu>
            </>
          );
        }
      },
    }),
  ];

  const defaultValues = {
    id: undefined,
    hisCode: "",
    startDate: new Date(),
    endDate: new Date(),
    atcCode: "",
    vbpClass: "",
    monitorClass: "",
    drugname: "",
    specification: "",
    miniUnit: "",
    packSize: 0,
    packUnit: "",
    pinyin: "",
    py: "",
    manuName: "",
    dutyAmount: 0,
    batch: "",
    cadn: "",
    calcFactor: 0,
    status: 0,
  };

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  const handleFormSubmit = async (data: FormValuesT) => {
    console.log(data);
    try {
      setIsSubmitting(true);
      if (data.id) {
        updateVbpBatch(data).then((res) => {
          run(searchParams.toString());
        });
      } else {
        createVbpBatch(data).then((res) => {
          run(searchParams.toString());
        });
      }
      setIsSubmitting(false);
      setIsDialogOpen(false);
      form.reset(defaultValues);
      toast({
        variant: "success",
        title: "数据提交成功",
        description: "",
        duration: 1600,
      });
    } catch (error: any) {
      toast({
        variant: "destructive",
        title: "数据提交失败",
        description: "请检查网络或联系系统管理员",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <PageContainer>
      <div className="space-y-4">
        {/* <Breadcrumbs items={breadcrumbItems} /> */}

        <div className="flex items-start justify-between">
          <Heading title={`药品集采批次列表`} description="" />

          <Button
            className="p-2 rounded-md hidden"
            onClick={() => {
              form.reset(defaultValues);
              setTitle("创建信息");
              setIsDialogOpen(!isDialogOpen);
            }}
          >
            <Plus className="mr-2 h-4 w-4" />
            创建
          </Button>
        </div>
        <Separator />

        <CustomDndTable
          columns={columns}
          initColumnVisibility={{ select: false, id: false }}
          defaultFilterColumn="drugname"
          loading={loadingList}
          data={vbpBatchList}
          totalCount={totalCount}
          showImportButton={true}
          onSubmitFiles={handleUploadSubmit}
        />

        <Dialog
          open={isDialogOpen}
          onOpenChange={() => setIsDialogOpen(!isDialogOpen)}
        >
          <DialogContent className="max-w-3xl h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle></DialogTitle>
              <DialogDescription></DialogDescription>
            </DialogHeader>
            <div className="flex items-center justify-between">
              <Heading title={title} description={description} />
            </div>
            <Separator />
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(handleFormSubmit)}
                className="w-full space-y-8"
              >
                <div className="flex flex-col gap-4">
                  {formData && formData.id ? (
                    <FormField
                      control={form.control}
                      name="id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>ID</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="id"
                              {...field}
                              disabled={formData && formData.id ? true : false}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  ) : (
                    <></>
                  )}
                  <FormField
                    control={form.control}
                    name="hisCode"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>HIS药品代码</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="HIS药品代码"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="drugname"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>药品名称</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="药品名称"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="specification"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>药品包装规格</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="药品包装规格"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="miniUnit"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>最小包装单位</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="最小包装单位"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="packSize"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>包装量</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            disabled={true}
                            placeholder="包装量"
                            // {...field}
                            onChange={(e) =>
                              field.onChange(e.target.valueAsNumber)
                            }
                            value={field.value}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="packUnit"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>包装单位</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="包装单位"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="startDate"
                    render={({ field }) => (
                      <FormItem className="flex flex-col">
                        <FormLabel>批次开始时间</FormLabel>
                        <FormControl>
                          <CustomDatePicker
                            value={field.value}
                            onChange={field.onChange}
                          />
                        </FormControl>
                        {/* <FormDescription>
                          Your date of birth is used to calculate your age.
                        </FormDescription> */}
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="endDate"
                    render={({ field }) => (
                      <FormItem className="flex flex-col">
                        <FormLabel>批次结束时间</FormLabel>
                        <FormControl>
                          <CustomDatePicker
                            value={field.value}
                            onChange={field.onChange}
                          />
                        </FormControl>
                        {/* <FormDescription>
                          Your date of birth is used to calculate your age.
                        </FormDescription> */}
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="dutyAmount"
                    // render={({ field }) => (
                    render={({ field: { onChange, value } }) => (
                      <FormItem>
                        <FormLabel>任务量</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            disabled={isSubmitting}
                            placeholder="任务量"
                            // {...field}
                            onChange={(e) => onChange(e.target.valueAsNumber)}
                            value={value}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="atcCode"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>药品ATC编码</FormLabel>
                        <FormControl>
                          <Input
                            disabled={isSubmitting}
                            placeholder="药品ATC编码"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="vbpClass"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>集采类型</FormLabel>
                        <FormControl>
                          <Input
                            disabled={isSubmitting}
                            placeholder="集采类型"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="monitorClass"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>监测类别</FormLabel>
                        <FormControl>
                          <Input
                            disabled={isSubmitting}
                            placeholder="监测类别"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="manuName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>生产厂商</FormLabel>
                        <FormControl>
                          <Input
                            disabled={isSubmitting}
                            placeholder="生产厂商"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="batch"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>批次名称</FormLabel>
                        <FormControl>
                          <Input
                            disabled={isSubmitting}
                            placeholder="批次名称"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="cadn"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>药品通用名</FormLabel>
                        <FormControl>
                          <Input
                            disabled={isSubmitting}
                            placeholder="药品通用名"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="calcFactor"
                    render={({ field: { onChange, value } }) => (
                      <FormItem>
                        <FormLabel>计算系数</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            disabled={isSubmitting}
                            placeholder="计算系数"
                            onChange={(e) => onChange(e.target.valueAsNumber)}
                            value={value}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="status"
                    render={({ field: { onChange, value } }) => (
                      <FormItem>
                        <FormLabel>统计状态</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            disabled={isSubmitting}
                            placeholder="统计状态"
                            onChange={(e) => onChange(e.target.valueAsNumber)}
                            value={value}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <Button
                  disabled={isSubmitting}
                  className="ml-auto"
                  type="submit"
                >
                  提交
                </Button>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>
    </PageContainer>
  );
};

export default page;
